package com.lhg.serve;

import java.io.IOException;
import java.io.InputStream;

public class HttpRequestHandler {

    public static HttpRequest getRequest(InputStream inputStream){

        StringBuilder request = new StringBuilder();
        try {
            byte[] buffer = new byte[1024 * 1024];
            int len;
             do {
                len = inputStream.read(buffer);
                 System.out.println(len);
                 if (len!=-1){
                     request.append(new String(buffer,0,len));
                 }
            }while (inputStream.available()>0);
        } catch (IOException  e) {
            e.printStackTrace();
        }

        System.out.println("request = " + request);
        HttpRequest httpRequest = new HttpRequest();
        String[] handAndBody = request.toString().split("\r\n\r\n");

        // 请求体
        if (handAndBody.length > 1 && handAndBody[1] != null) {
            httpRequest.setBody(handAndBody[1]);
        }

        String startAndHeader = handAndBody[0];

        String[] startAndHeaders = startAndHeader.split("\r\n");

        String startLine = startAndHeaders[0];

        String[] startLineElements = startLine.split(" ");
        httpRequest.setMethod(startLineElements[0]);


        String[] uriAndParams = startLineElements[1].split("\\?");
        if (uriAndParams.length>1 && uriAndParams[1]!=null){
            String[] params = uriAndParams[1].split("&");
            for (String s : params) {
                String[] param = s.split("=");
                httpRequest.setParameter(param[0], param[1]);
            }
        }
        httpRequest.setUri(startLineElements[1]);

        httpRequest.setProtocol(startLineElements[2]);

        //首部信息

        for (int i = 1; i < startAndHeaders.length; i++) {
            String header = startAndHeaders[i];

            String[] keyAndValue = header.split(":");

            httpRequest.setHeader(keyAndValue[0],keyAndValue[1]);
        }

        return httpRequest;
    }

}
